<?php
declare (strict_types = 1);

namespace app\admin\service;

use app\admin\model\AdminModel;

class RbacService extends BaseService
{
    /**
     * 权限认证
     *
     * @Author tanruizheng
     * @DateTime 2021-07-08
     * @param [type] $roleId
     * @param [type] $app
     * @param [type] $controller
     * @param [type] $action
     * @return array
     */
    public static function auth($roleId, $app, $controller, $action){
        //超级管理员
        if(AdminModel::SUPER_ADMIN_ROLE_ID == $roleId){
            return self::createSuccess('权限验证通过!');
        }
        //获取角色下的所有权限
        $accessList  = AccessService::getAccessList($roleId);
        $menuList = [];
        foreach ($accessList as $key => $value) {
            $menuList[$value['app']][$value['controller']][$value['action']] = $value['action'];
        }
        //权限验证通过
        if(isset($menuList['%']) && $menuList['%']){
            return self::createSuccess('权限验证通过!');
        }

        //无权限访问
        if(!isset($menuList[$app])){
            return self::createFail('无权限访问!');
        }

        if(isset($menuList[$app]['%'])){
            return self::createSuccess('权限验证通过!');
        }
        $controller = explode('.',$controller);
        foreach ($controller as $value) {
            $c[] = $value;
            $passController = trim(implode('.',$c).'.'.str_repeat('%',(count($controller)-count($c))),'.');
            if(
                isset($menuList[$app][$passController]) && (
                isset($menuList[$app][$passController][$action]) ||
                isset($menuList[$app][$passController]['%'])
            )){
                return self::createSuccess('权限验证通过!');
            }
        }
        return self::createFail('无权限访问!');
    }

}
